#!/userapp/build_python/bin/python
import subprocess
from configparser import ConfigParser
import os
import time

cfg = ConfigParser()
wifiselect = 'n'
ltdselect = 'n'
wifiSSID = ''
wifiPSWD = ''

res = subprocess.check_output('route -n', shell=True)
res = res.decode('utf-8')

ppplossCount = 0

while True:
    cfg.read('./netconfig.ini',encoding='utf8')
    if(cfg['user']['wifi'] == 'y'):
        wifiselect = 'y'
        if((cfg['user']['SSID'] != wifiSSID)|(cfg['user']['PSWD'] != wifiPSWD)):
            # open wlan0
            wifiSSID = cfg['user']['SSID']
            wifiPSWD = cfg['user']['PSWD']
            os.system('/usr/bin/cmd/wifi.sh -i wlan0 -s "%s" -p %s'%(wifiSSID,wifiPSWD))
            os.system('ifconfig eth0 up')
    else:
        if wifiselect == 'y' :
        # close wlan0
            os.system('ifconfig wlan0 down')
            wifiselect = 'n'
        wifiSSID = ''
        wifiPSWD = ''
    # time.sleep(10)

    if(cfg['user']['4g'] == 'y'):
        ltdselect = 'y'
        if 'ppp0' not in res:
            pppres = subprocess.check_output("ps -aux | grep 'pppd call'", shell=True)
            pppres = pppres.decode('utf-8')
            if '/userapp/build_pppd/sbin/pppd call gprs' not in pppres:
                print('pppres')
                os.system('cd /etc/ppp/peers')
                os.system('/userapp/build_pppd/sbin/pppd call gprs&')
            elif ppplossCount > 3:
                os.system('killall pppd')
            else:
                ppplossCount = ppplossCount + 1
        else:
            ppplossCount = 0
    else:
        if ltdselect == 'y':
            os.system('killall pppd')
            ltdselect = 'n'
    # time.sleep(10)

    # read route table
    time.sleep(10)
    print('========start scan route table=========')
    res = subprocess.check_output('route -n', shell=True)
    res = res.decode('utf-8')
    rel = res.splitlines()
    rel = rel[1:]
    rel2 = []
    flagfindeth0 = False
    eth0str = ''
    wlan0str = ''
    ppp0str = ''
    flageth0needR = True
    flagwlan0needR = True
    flagppp0needR = True
    for lines in rel:
        rel2 = lines.split()
        if rel2[1] != '0.0.0.0':
            if 'eth0' in rel2:
                flagfindeth0 = True
                # print(rel2[4])
                if rel2[4] != '100':
                    os.system('route del -net 0.0.0.0 dev eth0 metric %s'%(rel2[4]))
                    eth0str = 'route add -net 0.0.0.0 gw %s dev eth0 metric 100'%(rel2[1])
                else:
                    flageth0needR = False
            if wifiselect == 'y':
                if 'wlan0' in rel2:
                    if rel2[4] != '101':
                        os.system('route del -net 0.0.0.0 dev wlan0 metric %s'%(rel2[4]))
                        wlan0str = 'route add -net 0.0.0.0 gw %s netmask 0.0.0.0 dev wlan0 metric 101'%(rel2[1])
                    else:
                        flagwlan0needR = False
            else:
                flagwlan0needR = False
        # ppp0 rel2[1] == '0.0.0.0'
        if ltdselect == 'y':
            if 'ppp0' in rel2:
                if rel2[4] != '102':
                    if rel2[0] == '0.0.0.0':
                      os.system('route del -net 0.0.0.0 dev ppp0 metric %s'%(rel2[4]))
                    ppp0str = 'route add -net 0.0.0.0 netmask 0.0.0.0 dev ppp0 metric 102'
                else:
                    flagppp0needR = False
        else:
            flagppp0needR = False

    if flagfindeth0 == False:
        os.system('ifconfig eth0 up')
    if (eth0str!='') & flageth0needR:
        print(eth0str)
        os.system(eth0str)
    if (wlan0str!='') & flagwlan0needR:
        print(wlan0str)
        os.system(wlan0str)
    if (ppp0str!='') & flagppp0needR:
        print(ppp0str)
        os.system(ppp0str)
        